'use strict';
const Service = require('egg').Service;
// const Service = require('../Base/baseService');

class DanmuService extends Service {

	async update(sectionId, payload) {
		console.log("发送了弹幕", payload)
		const isHad = await this.ctx.model.Danmu.find({ 'sectionId': sectionId });
		if (!isHad.length) {
			await this.ctx.model.Danmu.create({ 'sectionId': sectionId, 'danmuList': [] })
		}

		const result = await this.ctx.model.Danmu.updateOne({ 'sectionId': sectionId }, {
			'$push': {
				'danmuList': payload
			}
		})

		return this.ctx.body = result
		// return this.ctx.body = payload

	}
	async find(sectionId) {
		const isHad = await this.ctx.model.Danmu.find({ 'sectionId': sectionId });
		if (!isHad.length) {
			await this.ctx.model.Danmu.create({ 'sectionId': sectionId, 'danmuList': [] })
		}
		const result = await this.ctx.model.Danmu.findOne({ 'sectionId': sectionId });

		var compare = function (prop) {
			return function (obj1, obj2) {
				var val1 = obj1[prop];
				var val2 = obj2[prop];
				if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
					val1 = Number(val1);
					val2 = Number(val2);
				}
				if (val1 < val2) {
					return -1;
				} else if (val1 > val2) {
					return 1;
				} else {
					return 0;
				}
			}
		}
		result.danmuList = result.danmuList.sort(compare('time'))
		console.log("获取了弹幕", sectionId)
		return this.ctx.body = result

	}

}

module.exports = DanmuService;
